#include "Block.h"

bool Block::Create(std::vector<D3DXVECTOR3> v,D3DXVECTOR3 centre)
{
	HRESULT hr;
	m_vCorners = v;
	int NumTris = v.size();
	int NumVerts =v.size()+1;
	m_vPos=centre;

	V(D3DXCreateMesh(NumTris,NumVerts,D3DXMESH_MANAGED,TheD3DApp::Instance()->GetVertexElements(),TheD3DApp::Instance()->GetD3DDev(),&m_pMesh));

	POSNORMUVVERTEX* pVertices;
	m_pMesh->LockVertexBuffer(0, (void**)&pVertices);

	pVertices[0].Pos=D3DXVECTOR3(0,0,0);
	pVertices[0].Norm=D3DXVECTOR3(0,1,0);
	pVertices[0].UV=D3DXVECTOR2(0,0);

	for (unsigned int i=0;i<v.size();++i)
	{
		pVertices[i+1].Pos=v[i]-m_vPos;
		pVertices[i+1].Norm=D3DXVECTOR3(0,1,0);
		pVertices[i+1].UV=D3DXVECTOR2(0,0);
	}
	m_pMesh->UnlockVertexBuffer();


	WORD *IndexData=NULL;
	V(m_pMesh->LockIndexBuffer( 0, (void**)&IndexData ));

	int indCount=0;
	for(unsigned int i=0; i<NumTris;++i)
	{
		IndexData[indCount++]=0;
		IndexData[indCount++]=i+1;
		if(i<NumTris-1)
		{
			IndexData[indCount++]=i+2;
		}
		else
		{
			IndexData[indCount++]=1;
		}
	}
	m_pMesh->UnlockIndexBuffer();

	for (unsigned int i=0;i<m_vCorners.size();++i)
	{
		Triangle t;
		if(i<m_vCorners.size()-1)
		{t=Triangle(m_vPos,m_vCorners[i],m_vCorners[i+1]);}
		else
		{t=Triangle(m_vPos,m_vCorners[i],m_vCorners[0]);}
		m_vRawTris.push_back(t);
	}

	while(!m_vRawTris.empty())
	{
		for (unsigned int i=0; i<m_vRawTris.size();++i)
		{
			D3DXVECTOR3 point = m_vRawTris[i].a;
			D3DXVECTOR3 sideMid = m_vRawTris[i].bc/2;
			D3DXVECTOR3 span = point-sideMid;
			float distance = D3DXVec3Length(&span);

			//cut this tri into 2 right angles
			if(distance>10)
			{
				//m_vPossibles.push_back(m_vRawTris[i]);
			}
			//try and use as is
			else if(distance>5)
			{

			}
		}
		m_vRawTris.clear();

		for (unsigned int i=0; i<m_vPossibles.size();++i)
		{
			D3DXVECTOR3 point = m_vPossibles[i].a;
			D3DXVECTOR3 sideMid = m_vPossibles[i].bc/2;
			D3DXVECTOR3 span = point-sideMid;
			float distance = D3DXVec3Length(&span);
			//if small enough to use
			if(distance<10)
			{
				m_vBuildAreas.push_back(m_vBuildAreas[i]);
			}
			//send back to raw tris
			else
			{
				Triangle t1(sideMid,point,m_vPossibles[i].b);
				Triangle t2(sideMid,point,m_vPossibles[i].c);
				m_vRawTris.push_back(t1);
				m_vRawTris.push_back(t2);
			}
		}
		m_vPossibles.clear();
	}

	//find where a building will fit
	for (unsigned int i=0;i<m_vBuildAreas.size();++i)
	{
		float length =D3DXVec3Length(&m_vBuildAreas[i].bc);
		if(length>3)
		float f = fmod(rand(),length-2)+1;
		float scale= f/length;
		scale*
	}

	return true;
}